package com.tqz.rocketmq.demo;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 消息的生产者
 * </p>
 *
 * @author tian
 * @since 2021/1/17 13:59
 */
public class Producer {

    public static void main(String[] args)
            throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer producer = new DefaultMQProducer(Constant.PRODUCER_GROUP);
        // 设置 NameServer 的地址，然后从该地址上面拿到Broker的地址
        producer.setNamesrvAddr(Constant.NAME_SERVER_ADDR);
        producer.setSendMsgTimeout(15000);

        // Rocket默认开启了VIP通道，VIP通道端口为10911-2=10909。
        // 若RocketMQ服务器未启动端口10909，则报connect to <> failed
//        producer.setVipChannelEnabled(false);

        // 启动
        producer.start();

        String body = "第%s条消息";
        int num = 1;
        while (num <= 10) {
            Message message = new Message(Constant.TOPIC, "test-tags", String.format(body, num).getBytes());

            producer.send(message, new SendCallback() {

                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println("有错误：" + e.getMessage());
                }
            });

            num++;
        }

        TimeUnit.SECONDS.sleep(20);

        // 停止
        producer.shutdown();
    }
}
